/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.mapper.BaseMapper;
import org.jbase.admin.dao.AdminRoleDao;
import org.jbase.admin.dao.AdminRoleMenuDao;
import org.jbase.admin.entity.AdminMenu;
import org.jbase.admin.entity.AdminRole;
import org.jbase.admin.entity.AdminRoleMenu;
import org.jbase.common.service.EntityMapperService;
import org.jbase.common.utils.Pager;
import org.jbase.common.utils.message.Message;
import org.jbase.common.utils.message.MessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project: jbase-springboot <br/>
 * File: AdminRoleService.java <br/>
 * Class: org.jbase.admin.service.AdminRoleService <br/>
 * Description: 系统角色. <br/>
 * Copyright: Copyright (c) 2016 <br/>
 * Company: http://git.oschina.net/liuzp315/Jbase <br/>
 * Makedate: 2016-12-29 12:19:49 <br/>
 * gen by Jbase Coder <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
@Service
public class AdminRoleService extends EntityMapperService<AdminRole> {

	@Autowired
	private AdminRoleDao adminRoleDao;

	@Autowired
	private AdminRoleMenuDao adminRoleMenuDao;

	@Autowired
	private AdminMenuService adminMenuService;

	@Override
	public BaseMapper<AdminRole> dao() {
		return adminRoleDao;
	}

	public Pager query(Map<String, String> map, Pager pager) {

		PageQuery<Object> pageQuery = new PageQuery<Object>(pager.getPageNumber(), map, -1, pager.getPageSize());
		adminRoleDao.selectPager(pageQuery);

		pager.setList(pageQuery.getList());
		pager.setRecordCount((int) pageQuery.getTotalRow());
		return pager;
	}

	public AdminRole fetchBySid(String sid) {
		return adminRoleDao.fetchBySid(sid);
	}

	public void deleteBySid(String sid) {
		adminRoleDao.deleteBySid(sid);
	}

	public Message<List<AdminRole>> listBySids(String sids) {
		Message<List<AdminRole>> mess = new Message<>();
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);

		if (StringUtils.isBlank(sids)) {
			return mess;
		}

		List<String> sqltemp = sids2list(sids);

		Map<String, Object> param = new HashMap<>();
		param.put("sids", sqltemp);
		List<AdminRole> listBySids = adminRoleDao.listBySids(param);

		mess.setData(listBySids);

		return mess;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param sids
	 * @param mess
	 * @return
	 */
	private List<String> sids2list(String sids) {
		List<String> sqltemp = new ArrayList<>();
		if (StringUtils.isBlank(sids)) {
			return sqltemp;
		}
		if (sids.startsWith(",")) {
			sids = sids.substring(1);
		}

		String[] split = sids.split(",");
		for (String str : split) {
			if (StringUtils.isNotBlank(str))
				sqltemp.add(str);
		}
		return sqltemp;
	}

	public Message<List<AdminRole>> allWithChecked(String sids) {

		Message<List<AdminRole>> all = all();

		if (StringUtils.isBlank(sids)) {
			return all;
		}

		List<String> lsid = sids2list(sids);

		List<AdminRole> data = all.getData();
		for (AdminRole ar : data) {
			if (lsid.contains(ar.getSid()))
				ar.set("isChecked", true);
			else
				ar.set("isChecked", false);
		}

		return all;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param id
	 * @return
	 */
	public List<AdminRole> listByAdminSid(String sid) {
		return adminRoleDao.listByAdminSid(sid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbase.common.service.EntityMapperService#doInsert(java.util.Map)
	 */
	@Override
	public Message<AdminRole> doInsert(Map<String, Object> map) {
		AdminRole ar = map2entity(map, new AdminRole());
		insertRoleMenu(map.get("menuSids"), ar);
		return insert(ar);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbase.common.service.EntityMapperService#doUpdate(java.util.Map, java.lang.String)
	 */
	@Override
	public Message<AdminRole> doUpdate(Map<String, Object> map, String entityId) {
		AdminRole ar = map2entity(map, unique(entityId).getData());

		adminRoleMenuDao.deleteByRoleSid(ar.getSid());
		insertRoleMenu(map.get("menuSids"), ar);

		return updateById(ar);
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param rsids
	 * @param role
	 */
	private void insertRoleMenu(Object rsids, AdminRole role) {
		if (rsids != null && StringUtils.isNotBlank(rsids.toString())) {
			List<AdminRoleMenu> list = new ArrayList<>();
			List<AdminMenu> listBySids = adminMenuService.listBySids(rsids.toString()).getData();
			for (AdminMenu menu : listBySids) {
				AdminRoleMenu aur = new AdminRoleMenu();
				aur.setMenuId(menu.getId());
				aur.setMenuSid(menu.getSid());
				aur.setMenuName(menu.getName());
				aur.setRoleId(role.getId());
				aur.setRoleSid(role.getSid());
				aur.setRoleName(role.getName());
				list.add(aur);
			}
			sql.insertBatch(AdminRoleMenu.class, list);
		}
	}

	@Override
	public Message<Integer> deleteById(Object key) {
		AdminRole ar = adminRoleDao.unique(key);
		adminRoleMenuDao.deleteByRoleSid(ar.getSid());
		return super.deleteById(key);
	}
}
